<template>
    <div>
        <el-drawer size="500" :visible.sync="personalSetting" :with-header="false" :before-close="handleClose">
            <div class="drawer__content">
                <div class="user-profile-info">
                    <div class="drawer__content_top">
                        <div class="drawer__content_close">
                            <el-button icon="el-icon-close" type="text" @click="handleClose"></el-button>
                        </div>
                        <el-row>
                            <el-col :span="7">
                                <el-image v-if="userProfile.header" class="avatar-image" :src="userProfile.header"/>
                            </el-col>
                            <el-col :span="17">
                                <div class="avatar-label">
                                    <div>
                                        <i class="el-icon-user"></i>&nbsp;&nbsp;
                                        {{userProfile.name}}
                                        <i class="el-icon-female" v-if="userProfile.sex"></i>
                                        <i class="el-icon-male" v-else></i>
                                    </div>
                                    <div :title="userProfile.roleName">
                                        <i class="el-icon-postcard"></i>&nbsp;&nbsp;{{userProfile.roleName}}
                                    </div>
                                    <div :title="userProfile.signName">
                                        <i class="el-icon-edit"></i>&nbsp;&nbsp;
                                        {{userProfile.signName}}
                                    </div>
                                    <div title="邮箱">
                                        <i class="el-icon-message"></i>&nbsp;&nbsp;
                                        {{userProfile.email}}
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <el-tabs v-model="activeTabName" @tab-click="switchTab" :stretch="true">
                    <el-tab-pane name="chat">
                        <span slot="label">
                           <el-badge :value="chatTotalNumber" :hidden="chatTotalNumber === 0" :max="99">
                                <i title="聊天记录" class="tab-icon el-icon-chat-dot-square"></i>
                            </el-badge>
                        </span>
                        <div class="message-list">
                            <div class="chat-user" v-for="(item,index) in chatUsers" :key="index"
                                 @click="openChatDialog(item)" v-if="chatUsers.length">
                                <div class="chat-user-header">
                                    <el-image class="image" :src="fileDownloadAction+item.header"></el-image>
                                </div>
                                <div class="chat-user-user-info">
                                    <div class="chat-user-user-name">
                                        {{item.name}}
                                        <el-divider direction="vertical"></el-divider>&nbsp;{{item.sendTime}}
                                    </div>
                                    <div class="chat-user-user-msg">
                                        {{item.msgContent}}
                                    </div>
                                </div>
                                <el-badge :value="item.unReadCount" v-if="item.unReadCount"
                                          class="user-msg-number"></el-badge>
                                <div class="chat-user-operate" style="visibility: hidden"
                                     @click.stop="removeOneMsg(item)">
                                    删除
                                </div>
                            </div>
                            <div v-else class="no-chat-user">
                                无消息
                            </div>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane name="communicationList">
                        <span slot="label"><i title="通讯录" class="tab-icon el-icon-user"></i></span>
                        <contract-users :user-list="contractUsers" :file-down-url="fileDownloadAction"
                                        @chooseUserCallBack="chooseUserCallBack"
                                        @filterUserCallBack="filterUserCallBack"></contract-users>
                    </el-tab-pane>
                    <el-tab-pane name="group">
                        <span slot="label"><i title="群组" class="tab-icon el-icon-userGroup"></i></span>
                        <contract-group :group-list="contractGroups" :file-down-url="fileDownloadAction"
                                        @chooseUserCallBack="chooseUserCallBack"></contract-group>
                    </el-tab-pane>
                    <el-tab-pane name="updateUser">
                        <span slot="label"><i title="设置个人信息" class="tab-icon el-icon-set-up"></i></span>
                        <el-form :model="userForm" :rules="rules" ref="userForm" label-width="80px"
                                 style="padding: 10px;">
                            <el-form-item label="个性签名" prop="signName">
                                <el-input size="medium" v-model="userForm.signName"></el-input>
                            </el-form-item>
                            <el-form-item label="新头像" prop="header">
                                <el-upload class="avatar-uploader" :action="fileUploadAction"
                                           :show-file-list="false"
                                           :on-success="handleAvatarSuccess"
                                           :before-upload="beforeAvatarUpload">
                                    <img v-if="userForm.header" :src="userForm.header" class="avatar-image">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </el-form-item>
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="性别" prop="sex">
                                        <el-radio v-model="userForm.sex" label="false">
                                            <i class="el-icon-male"></i>
                                        </el-radio>
                                        <el-radio v-model="userForm.sex" label="true">
                                            <i class="el-icon-female"></i>
                                        </el-radio>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="修改密码">
                                        <el-switch v-model="updPwdFlag">
                                        </el-switch>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-form-item label="登录名" prop="loginName">
                                <el-input size="medium" placeholder="请输入登录名" v-model="userForm.loginName"></el-input>
                            </el-form-item>
                            <el-form-item label="用户名" prop="name" label-width="">
                                <el-input size="medium" placeholder="请输入用户名" v-model="userForm.name"></el-input>
                            </el-form-item>
                            <el-form-item label="邮箱" prop="email" label-width="">
                                <el-input size="medium" placeholder="请输入邮箱" v-model="userForm.email"></el-input>
                            </el-form-item>
                            <el-form-item v-if="updPwdFlag" label="旧密码" prop="password">
                                <el-input size="medium" v-model="userForm.password" placeholder="请输入旧密码"
                                          type="password"></el-input>
                            </el-form-item>
                            <el-form-item v-if="updPwdFlag" size="medium" label="新密码" prop="newPassword">
                                <el-input v-model="userForm.newPassword" placeholder="请输入新密码"
                                          type="password"></el-input>
                            </el-form-item>
                            <el-form-item v-if="updPwdFlag" size="medium" label="确认密码" prop="confirmPassword">
                                <el-input v-model="userForm.confirmPassword" placeholder="请再次输入新密码"
                                          type="password"></el-input>
                            </el-form-item>
                        </el-form>
                        <div class="profile-drawer__footer">
                            <el-button style="width: 48%;" @click="handleResetUserInfo()" size="small">重 置
                            </el-button>
                            <el-button style="width: 48%;" type="primary" @click="handleUpdateUserInfo('userForm')"
                                       :loading="loading" size="small">
                                保 存
                            </el-button>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-drawer>
        <transition name="bounce" mode="out-in">
            <chat-room @callBackFromSub="callBackFromSub"
                       :choose-chat-user="chooseChatUser" :chat-dialog-visible="chatDialogVisible"
                       :file-download-url="fileDownloadAction" :file-upload-url="fileUploadAction">
            </chat-room>
        </transition>
    </div>
</template>

<script>
    import ChatRoom from "../../views/chat/ChatRoom"
    import ContractUsers from "../../views/chat/ContractUsers"
    import ContractGroup from "../../views/chat/ContractGroup"

    export default {
        name: "UserProfile",
        components: {
            ChatRoom,
            ContractUsers,
            ContractGroup
        },
        props: {
            personalSetting: {
                type: Boolean,
                default: false,
                required: true
            },
            userProfile: {
                type: Object,
                default: {},
                required: true
            }
        },
        computed: {
            chatTotalNumber() {
                let totalNumber = 0;
                this.chatUsers.forEach(o => {
                    totalNumber += o ? o.unReadCount : 0;
                });
                return totalNumber;
            }
        },
        data() {
            let validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.userForm.newPassword) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                headMouseHover: false,
                loading: false,
                isCollapse: false,
                chooseChatUser: {},
                chatDialogVisible: false,
                fileUploadAction: this.$commonUrlHttp + "api/rest/file/upload?path=user_head",
                fileDownloadAction: this.$commonUrlHttp + "api/rest/file/download/",
                activeTabName: 'chat',
                chatUsers: [],//聊天列表
                contractUsers: [],//通讯录人员列表
                contractGroups: [],//用户组列表
                updPwdFlag: false,
                userForm: {
                    id: '',
                    name: '',
                    loginName: '',
                    email: '',
                    password: '',
                    newPassword: '',
                    confirmPassword: '',
                    header: '',
                    sex: "false",
                    signName: ""
                },
                rules: {
                    name: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    loginName: [
                        {required: true, message: '请输入登录名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 1, max: 10, message: '长度在1到10个字符', trigger: 'blur'}
                    ],
                    newPassword: [
                        {required: true, message: '请输入新密码', trigger: 'blur'},
                        {min: 6, max: 10, message: '长度在6到10个字符', trigger: 'blur'}
                    ],
                    confirmPassword: [
                        {validator: validatePass, trigger: 'blur'}
                    ],
                }
            }
        },
        methods: {
            //通讯录选择回调
            chooseUserCallBack(param) {
                //调用聊天弹窗
                this.openChatDialog(param);
                //调用更新聊天记录为已读
                this.handleMsgRead(param);
            },
            //筛选用户
            filterUserCallBack(param) {

            },
            //打开聊天弹窗
            openChatDialog(param) {
                this.chooseChatUser = param;
                this.chatDialogVisible = true;
                this.$store.commit("pushDialogUser", param);
                //调用更新聊天记录为已读
                this.handleMsgRead(param);
            },
            //切换tab
            switchTab(tab) {
                switch (tab.name) {
                    case "chat":
                        this.loadChatList();
                        break;
                    case "communicationList":
                        this.loadContractList();
                        break;
                    case "group":
                        this.loadGroupList();
                        break;
                    case "notice":
                        break;
                    case "updateUser":
                        this.handleResetUserInfo();
                        break;
                }
            },
            //加载化聊天列表
            loadChatList() {
                //查询数据库中的聊天列表
                this.$httpGet(this.$axiosIMInstance, "api/rest/imChatRecord/list", {
                    receiverId: this.userProfile.id
                }).then(res => {
                    if (res.code === 200) {
                        this.chatUsers = res.data;
                    }
                });
            },
            //加载通讯录
            loadContractList() {
                this.$httpGet(this.$axiosBaseHttp, "api/rest/userInfo/list", {}).then(res => {
                    if (res.code === 200) {
                        this.contractUsers = res.data;
                    }
                })
            },
            //加载用户组
            loadGroupList() {
                this.$httpGet(this.$axiosBaseHttp, "api/rest/userGroupInfo/list", {}).then(res => {
                    if (res.code === 200) {
                        this.contractGroups = res.data;
                    }
                })
            },
            //更新消息为已读
            handleMsgRead(param) {
                if (param) {
                    this.$httpPut(this.$axiosIMInstance, "api/rest/imChatRecord/updRead", {
                        senderId: param.id,
                        receiverId: this.userProfile.id,
                        isRead: 1
                    }).then(res => {
                        if (res.code === 200) {
                            this.$emit("callBackFromSub", true);
                        }
                    });
                }
            },
            //删除消息记录
            removeOneMsg(param) {
                if (param) {
                    this.$httpDelete(this.$axiosIMInstance, "api/rest/imChatRecord/del", {
                        senderId: param.id,
                        receiverId: this.userProfile.id,
                        isRead: 1,
                        isDeleted: 1
                    }).then(res => {
                        if (res.code === 200) {
                            this.chatUsers.splice(this.chatUsers.indexOf(param), 1);
                            this.$emit("callBackFromSub", true);
                        }
                    });
                }
            },
            //侧边导航栏收缩
            asideToggle(param) {
                this.isCollapse = param;
                this.$emit('collapseFromHeader', this.isCollapse);
            },
            //上传成功
            handleAvatarSuccess(res, file) {
                if (res.code === 200) {
                    this.userForm.header = this.fileDownloadAction + res.data.code;
                }
            },
            //上传之前
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //编辑用户信息
            handleResetUserInfo() {
                this.userForm = {...this.userProfile};
            },
            handleUpdateUserInfo(formName) {
                const arr = this.userForm.header.split("/");
                const param = _.assign({}, this.userForm, {header: arr[arr.length - 1]});
                this.loading = true;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.userForm.id) {
                            this.$httpPut(this.$axiosBaseHttp, "api/rest/userInfo/upd/byOne", param).then(res => {
                                if (res.code === 200) {
                                    this.$successMsg("保存成功");
                                    //更新缓存中的数据
                                    sessionStorage.setItem("currLoginUser", JSON.stringify({
                                        id: res.data.id,
                                        loginName: res.data.loginName,
                                        name: res.data.name,
                                        roleName: res.data.roleName,
                                        header: this.$commonUrlHttp + "api/rest/file/download/" + res.data.header,
                                        sex: res.data.sex,
                                        signName: res.data.signName,
                                        email: res.data.email
                                    }));
                                } else {
                                    this.$errorMsg("保存失败");
                                }
                                this.loading = false;
                            });
                        }
                    } else {
                        this.loading = false;
                        return false;
                    }
                });
            },
            //处理头像鼠标hover事件
            handlerHeaderHover(param) {
                this.headMouseHover = param;
            },
            //关闭抽屉
            handleClose() {
                this.$emit("callBackFromSub", false);
            },
            //来自 ChatRoom 子组件方法回调
            callBackFromSub(param) {
                this.chatDialogVisible = param;
                this.chooseChatUser = {};
            }
        },
        mounted() {
            let _this = this;
            _this.loadChatList();
            //监听ws数据响应
            window.addEventListener('onmessageWS', function (e) {
                if (e.detail.messageEvent.data !== "pong") {
                    _this.loadChatList();
                }
            });
        }, destroyed() {
            window.removeEventListener('onmessageWS', function (e) {
            });
        }
    }
</script>

<style scoped lang="scss">
    .drawer__content {
        background: rgba(255, 255, 255, 1);
        height: calc(100vh);
        width: 500px;

        /deep/ .el-tabs__header {
            margin: 0 0 10px;
        }

        /deep/ .el-tabs__item {
            text-align: center;
            width: 125px;
            padding: 0 10px;

            .el-badge__content.is-fixed {
                top: 8px;
            }

            .tab-icon {
                font-size: 25px;
            }

        }

        .user-profile-info {
            background: rgba(255, 255, 255, 1);
            /*background-image: linear-gradient(160deg, rgba(255, 56, 226, 0.13) 20%, rgba(0, 179, 255, 0.67) 80%);*/
        }

        .message-list {
            color: #333333;
            overflow-y: scroll;
            height: calc(100vh - 240px);

            .no-chat-user {
                width: 100%;
                height: 20px;
                color: #8c939d;
                font-size: 14px;
                line-height: 20px;
                text-align: center;
            }

            .chat-user:hover {
                cursor: pointer;
                background-color: rgba(12, 23, 35, 0.04);

                .user-msg-number {
                    visibility: hidden;
                }

                .chat-user-operate {
                    background: #ffaa43;
                    overflow: hidden;
                    color: #ffffff;
                    text-align: center;
                    animation: chat-user-operate-transmission 400ms;
                    -webkit-animation: chat-user-operate-transmission 400ms;
                    animation-iteration-count: 1;
                    animation-fill-mode: forwards;
                }

                @keyframes chat-user-operate-transmission {
                    from {
                        width: 40px;
                        visibility: hidden;
                        text-align: center;
                        height: 60px;
                        right: 0;
                    }
                    to {
                        width: 60px;
                        display: block;
                        height: 60px;
                        visibility: visible;
                        right: 100px;
                    }
                }
            }

            .chat-user {
                display: flex;

                .chat-user-header {
                    height: 60px;
                    width: 60px;
                    border-radius: 60px;
                    padding: 5px 5px;

                    .image {
                        height: 45px;
                        width: 45px;
                        border-radius: 45px;
                    }
                }

                .chat-user-user-info {
                    width: 382px;

                    .chat-user-user-name {
                        height: 26px;
                        line-height: 26px;
                        padding: 2px 2px 2px 5px;
                        font-size: 14px;
                    }

                    .chat-user-user-msg {
                        width: 330px;
                        height: 30px;
                        line-height: 30px;
                        padding-left: 5px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        font-size: 13px;
                        color: #8c939d
                    }
                }

                .user-msg-number {
                    line-height: 60px;
                }

            }
        }

        .drawer__content_close {
            text-align: right;
            padding-right: 15px;
        }

        .drawer__content_top {
            position: relative;
            background-image: linear-gradient(190deg, rgba(16, 74, 255, 0.25) 25%, rgba(0, 179, 255, 0.25) 75%);
            overflow: hidden;
            text-align: center;

            .avatar-uploader {
                height: 100px;
            }

            .avatar-label {
                color: #333333;

                div {
                    height: 30px;
                    line-height: 30px;
                    text-align: left;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }

            }
        }
    }

    .el-icon-male {
        color: #409eff;
        font-size: 18px;
    }

    .el-icon-female {
        color: #ff38e2;
        font-size: 18px;
    }

    .drawer__footer {
        padding-right: 0;
        text-align: center;

        button {
            width: 40%;
        }
    }

    .header-right {
        line-height: 60px;
        height: 60px;
    }

    .header-right {
        flex: 0 0 40px;

        .el-avatar--circle {
            margin-top: 1vh;
        }
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 16px;
        color: #8c939d;
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
    }

    .avatar-image {
        width: 100px;
        height: 100px;
        border-radius: 100px;
    }

    .avatar-image:hover, .avatar-image-hover:hover {
        cursor: pointer;
    }

    .avatar-image-hover {
        background: rgba(0, 0, 0, 0.3);
        height: 100px;
        width: 100px;
        position: absolute;
        top: 0;
        left: 23px;
        border-radius: 100px;
    }

    .profile-drawer__footer {
        text-align: center;
    }

    /*修改滚动条样式--start*/
    .message-list::-webkit-scrollbar {
        width: 5px;
        height: 10px;
        display: none;
    }

    .message-list::-webkit-scrollbar-track {
        background: rgb(239, 239, 239);
        border-radius: 2px;
    }

    .message-list::-webkit-scrollbar-thumb {
        background: #bfbfbf;
        border-radius: 10px;
    }

    .message-list::-webkit-scrollbar-thumb:hover {
        background: rgba(39, 161, 255, 0.92);
    }

    .message-list::-webkit-scrollbar-corner {
        background: rgba(39, 161, 255, 0.92);
    }

    /*修改滚动条样式--end*/

    /*  动画特效--begin  */
    .fade-enter-active, .fade-leave-active {
        transition: opacity .5s;
    }

    .fade-enter, .fade-leave-to {
        opacity: 0;
    }

    .bounce-enter-active {
        animation: bounce-in .3s;
    }

    .bounce-leave-active {
        animation: bounce-in .3s reverse;
    }

    @keyframes bounce-in {
        0% {
            transform: scale(0);
        }
        100% {
            transform: scale(1);
        }
    }

    /*  动画特效--end  */
</style>
